import 'package:any_reader/view_model/reader_model.dart';
import 'package:any_reader/views/reader/reader_theme.dart';
import 'package:connectivity/connectivity.dart';
import 'package:draggable_scrollbar/draggable_scrollbar.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_inner_drawer/inner_drawer.dart';

import '../../public.dart';
import 'components/reader_view.dart';
import 'components/reder_view_scroll.dart';

class ReaderPage extends StatefulWidget {
  final String bookId;
  final String catalogId;
  final String num;
  final String position;

  ReaderPage({Key key, this.bookId, this.catalogId, this.num, this.position})
      : super(key: key);

  @override
  _ReaderPageState createState() => _ReaderPageState();
}

class _ReaderPageState extends State<ReaderPage> with TickerProviderStateMixin {
  final GlobalKey<InnerDrawerState> _innerDrawerKey =
      GlobalKey<InnerDrawerState>();

  ScrollController _customController = ScrollController();
  PageController pageController = PageController(keepPage: false);

  bool innerDrawerIsOpen = false;
  bool showToolBar = false;
  Animation<RelativeRect> animationOut; //动画对象
  AnimationController controllerOut; //动画控制器

  Animation<RelativeRect> animationEnter; //动画对象
  AnimationController controllerEnter; //动画控制器

  Animation<RelativeRect> animationCustomNavigatorOut; //动画对象
  AnimationController customNavigatorControllerOut;

  Animation<RelativeRect> animationCustomNavigatorEnter; //动画对象
  AnimationController customNavigatorControllerEnter;
  double itemHeight = ScreenUtil().setHeight(100);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
//    pageController.addListener(onScroll);
  }

  void initAnimation() {
    controllerEnter = AnimationController(
        duration: const Duration(milliseconds: 150), vsync: this);
    controllerOut = AnimationController(
        duration: const Duration(milliseconds: 150), vsync: this);

    customNavigatorControllerEnter = AnimationController(
        duration: const Duration(milliseconds: 150), vsync: this);
    customNavigatorControllerOut = AnimationController(
        duration: const Duration(milliseconds: 150), vsync: this);
    RelativeRectTween rectTweenEnter = RelativeRectTween(
        begin: RelativeRect.fromLTRB(0, ScreenUtil().setHeight(1334), 0, 0),
        end: RelativeRect.fromLTRB(0,
            ScreenUtil().setHeight(1334) - ScreenUtil().setHeight(420), 0, 0));

    RelativeRectTween rectTweenOut = RelativeRectTween(
        begin: RelativeRect.fromLTRB(0,
            ScreenUtil().setHeight(1334) - ScreenUtil().setHeight(420), 0, 0),
        end: RelativeRect.fromLTRB(0, ScreenUtil().setHeight(1334), 0, 0));

    RelativeRectTween rectCustomNavigatorAnimationEnter = RelativeRectTween(
        begin: RelativeRect.fromLTRB(0, 0, 0, ScreenUtil().setHeight(1334)),
        end: RelativeRect.fromLTRB(0, 0, 0,
            ScreenUtil().setHeight(1334) - ScreenUtil().setHeight(130)));

    RelativeRectTween rectCustomNavigatorAnimationOut = RelativeRectTween(
        begin: RelativeRect.fromLTRB(0, 0, 0,
            ScreenUtil().setHeight(1334) - ScreenUtil().setHeight(130)),
        end: RelativeRect.fromLTRB(0, 0, 0, ScreenUtil().setHeight(1334)));

    animationEnter = rectTweenEnter.animate(controllerEnter);
    animationEnter.addStatusListener((status) {
      print(status);
      if (status == AnimationStatus.completed) {
//        controllerEnter.stop();
        sleep(Duration(milliseconds: 1));
        setState(() {
          showToolBar = true;
        });
      }
    });
    animationOut = rectTweenOut.animate(controllerOut);
    animationOut.addStatusListener((status) {
      print(status);
      if (status == AnimationStatus.completed) {
//        controllerOut.stop();
        sleep(Duration(milliseconds: 1));
        setState(() {
          showToolBar = false;
        });
      }
    });
    animationCustomNavigatorEnter = rectCustomNavigatorAnimationEnter
        .animate(customNavigatorControllerEnter);
    animationCustomNavigatorEnter.addStatusListener((status) {
      print(status);
      if (status == AnimationStatus.completed) {
        sleep(Duration(milliseconds: 1));
      }
    });

    animationCustomNavigatorOut =
        rectCustomNavigatorAnimationOut.animate(customNavigatorControllerOut);
    animationCustomNavigatorOut.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        sleep(Duration(milliseconds: 1));
      }
    });
  }

  void setDisplayToolBar({Color statusBarColor, int backgroundType}) {
    if (mounted) {
      if (showToolBar) {
        controllerOut.forward();
        controllerEnter.reset();
        FlutterStatusbarManager.setHidden(true);
        FlutterStatusbarManager.setColor(statusBarColor);

        customNavigatorControllerOut.forward();
        customNavigatorControllerEnter.reset();
      } else {
        controllerEnter.forward();
        controllerOut.reset();
        FlutterStatusbarManager.setHidden(false);
        FlutterStatusbarManager.setColor(statusBarColor);
        customNavigatorControllerEnter.forward();
        customNavigatorControllerOut.reset();
      }
      if (backgroundType != 1) {
        FlutterStatusbarManager.setStyle(StatusBarStyle.DARK_CONTENT);
      } else {
        FlutterStatusbarManager.setStyle(StatusBarStyle.LIGHT_CONTENT);
      }
    }
  }

//  HideAlways
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: ProviderWidget<ReaderModel>(
          model: ReaderModel(Provider.of<ThemeModel>(context)),
          onModelReady: (model) async => model.initData(
              bookId: widget.bookId,
              catalogId: widget.catalogId,
              num: widget.num,
              position: widget.position,
              pageController: pageController,
              call: initAnimation),
          builder: (context, model, child) {
            return () {
              if (model.busy) {
                return ViewStateBusyWidget();
              } else if (model.error) {
                return ViewStateWidget(onPressed: model.initData);
              }
              return InnerDrawer(
                key: _innerDrawerKey,
                position: InnerDrawerPosition.start, // required
                onTapClose: true, // default false
                swipe: false, // default true
                offset: 0.4, // default 0.4
                animationType: InnerDrawerAnimation.linear, // default static
                innerDrawerCallback: (bool value) {
                  setState(() {
                    innerDrawerIsOpen = value;
                  });

                  if (value) {
                    //如果切换状态时是打开状态，那么跳转到当前章节。
                    _customController.animateTo(
                        model.chapterIndex.toDouble() * itemHeight,
                        duration: new Duration(milliseconds: 500),
                        curve: Curves.ease);
                  }
                }, // return bool
                child: GestureDetector(
                    onHorizontalDragDown: (DragDownDetails details) {
                      _innerDrawerKey.currentState.dragDown(details);
                    },
                    onHorizontalDragUpdate: (DragUpdateDetails details) {
                      _innerDrawerKey.currentState.dragMove(details);
                    },
                    onHorizontalDragEnd: (DragEndDetails details) {
                      _innerDrawerKey.currentState.dragEnd(details);
                    },
                    child: Material(
                      color: model.theme.background,
                      child: model.chapterList.length > 0
                          ? _buildChapterContent(model)
                          : ViewStateBusyWidget(),
                    )),
                scaffold: Scaffold(
                  body: WillPopScope(
                    onWillPop: _willPopHandle,
                    //如果要扩展阅读模式，请从这里开始扩展
                    child: Stack(
                      children: <Widget>[
                        Container(
                          height: ScreenUtil().setHeight(1334),
                          decoration: model.theme.type == 0
                              ? BoxDecoration(
                                  image: new DecorationImage(
                                      image: new AssetImage(
                                          "assets/images/book_bg_normal.png"),
                                      fit: BoxFit.fill
                                      //这里是从assets静态文件中获取的，也可以new NetworkImage(）从网络上获取
                                      ))
                              : BoxDecoration(color: model.theme.background),
                          child: () {
                            if (model.busy) {
                              return ViewStateBusyWidget();
                            } else {
                              return model.readMode == ReadMode.scroll
                                  ? _buildScrollView(model)
                                  : _buildPageView(model);
                            }
                          }(),
                        ),
                        _buildLeftAction(model),
                        _buildRightAction(model),
                        _buildCenterAction(model),
                        _buildToolBar(model),
                        _customNavigator(model),
                        _buildForceButton(model),
                      ],
                    ),
                  ),
                ),
              );
            }();
          }),
    );
  }

  Widget _buildForceButton(ReaderModel model) {
    return !showToolBar
        ? Container()
        : Positioned(
            bottom: ScreenUtil().setHeight(550),
            right: ScreenUtil().setWidth(50),
            width: ScreenUtil().setWidth(100),
            height: ScreenUtil().setWidth(100),
            child: GestureDetector(
              onTap: () {
                model.refresh(
                  1,
                  catalogId: model.articleList[0].nextCatalogId,
                  catalogNum: model.articleList[0].nextCatalogNum,
                  forceServer: true,
                );
              },
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: model.theme.expandBackground,
                    borderRadius: BorderRadius.circular(100),
                    boxShadow: [
                      BoxShadow(
                        color: model.theme.expandActive.withOpacity(0.1),
                        offset: Offset(0.0, -2.0),
                        spreadRadius: 0.0,
                        blurRadius: 5.0,
                      )
                    ]),
                child: Text(
                  "章节\n错误",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: model.theme.text.withOpacity(0.7),
                    fontSize:
                        ScreenUtil().setSp(30, allowFontScalingSelf: true),
                    fontFamily: "xiaowei",
                  ),
                ),
              ),
            ),
          );
  }

  Widget _buildRightAction(ReaderModel model) {
    if (model.articleList[1].pageCount < 1) {
      return Container(
        width: 0,
        height: 0,
        color: Colors.white,
      );
    } else {
      return model.readMode == ReadMode.scroll
          ? Positioned(
              width: ScreenUtil().setWidth(750 / 2),
              height: ScreenUtil().setHeight(1334),
              right: ScreenUtil().setWidth(0),
              top: ScreenUtil().setWidth(0),
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onDoubleTap: () {
                  _innerDrawerKey.currentState.open();
                },
                onTap: () {
                  if (!showToolBar) {
                    model.nextPage();
                  }
                },
              ),
            )
          : Positioned(
              width: ScreenUtil().setWidth(750 / 2),
              height: ScreenUtil().setHeight(1334),
              right: ScreenUtil().setWidth(0),
              top: ScreenUtil().setWidth(0),
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onDoubleTap: () {
                  _innerDrawerKey.currentState.open();
                },
                onTap: () {
//                  if (!showToolBar) {
//                    model.nextPage();
//                  }
                },
                onVerticalDragStart: (DragStartDetails d) {},
              ),
            );
    }
  }

  Widget _buildCenterAction(ReaderModel model) {
    if (model.articleList[1].pageCount < 1) {
      return Container(
        width: 0,
        height: 0,
        color: Colors.white,
      );
    } else {
      return model.articleList[1].pageCount < 1
          ? Positioned(child: Container())
          : Positioned(
              width: ScreenUtil().setWidth(600),
              height: ScreenUtil().setWidth(700),
              left: ScreenUtil().setWidth(75),
              top: ScreenUtil().setWidth(400),
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onDoubleTap: () {
                  _innerDrawerKey.currentState.open();
                },
                onTap: () {
                  setState(() {
                    setDisplayToolBar(
                        backgroundType: model.theme.type,
                        statusBarColor: model.theme.expandBackground);
                  });
                },
              ),
            );
    }
  }

  Widget _buildLeftAction(ReaderModel model) {
    if (model.articleList[1].pageCount < 1) {
      return Container(
        width: 0,
        height: 0,
        color: Colors.white,
      );
    } else {
      return model.readMode == ReadMode.scroll
          ? Positioned(
              width: ScreenUtil().setWidth(750 / 2),
              height: ScreenUtil().setHeight(1334),
              left: ScreenUtil().setWidth(0),
              top: ScreenUtil().setWidth(0),
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onDoubleTap: () {
                  _innerDrawerKey.currentState.open();
                },
                onTap: () {
                  if (!showToolBar) {
                    model.previousPage();
                  }
                },
              ),
            )
          : Positioned(
              width: ScreenUtil().setWidth(750 / 2),
              height: ScreenUtil().setHeight(1334),
              left: ScreenUtil().setWidth(0),
              top: ScreenUtil().setWidth(0),
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onDoubleTap: () {
                  _innerDrawerKey.currentState.open();
                },
                onTap: () {
//                  if (!showToolBar) {
//                    model.previousPage();
//                  }
                },
                onVerticalDragStart: (DragStartDetails d) {},
              ),
            );
    }
  }

  Widget _buildToolBar(ReaderModel model) {
    return PositionedTransition(
      rect: showToolBar ? animationOut : animationEnter,
      child: Container(
        height: ScreenUtil().setHeight(500),
        decoration: BoxDecoration(
            color: model.theme.expandBackground,
            boxShadow: [
              BoxShadow(
                color: model.theme.expandBackground,
                offset: Offset(0.0, -2.0),
                spreadRadius: 0.0,
                blurRadius: 10.0,
              )
            ],
            border:
                Border(top: BorderSide(color: model.theme.text, width: 0.1))),
        child: Column(
          children: <Widget>[
            Container(
              height: ScreenUtil().setHeight(100),
              padding: EdgeInsets.fromLTRB(10, 20, 10, 10),
              child: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Text("字体",
                        style: TextStyle(
                            color: model.theme.text,
                            fontSize: ScreenUtil()
                                .setSp(24, allowFontScalingSelf: true))),
                  ),
                  Expanded(
                    flex: 5,
                    child: Slider(
                      value: model.readerConfig.fontSize,
                      min: 12,
                      max: 24,
                      activeColor: model.theme.expandText,
                      inactiveColor: model.theme.expandActive,
                      divisions: 12,
                      label:
                          "${(model.readerConfig.fontSize.floor()).toString()}",
                      onChanged: (double val) {
                        print(val);
                        model.readerConfig.fontSize = val;
                        setState(() {});
                      },
                      onChangeEnd: (double val) {
                        model.setConfig(kReaderFrontSize, val);
//                        setState(() {});
                      },
                    ),
                  )
                ],
              ),
            ),
            Container(
              height: ScreenUtil().setHeight(100),
              padding: EdgeInsets.fromLTRB(10, 20, 10, 10),
              child: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Text("行间距",
                        style: TextStyle(
                            color: model.theme.text,
                            fontSize: ScreenUtil()
                                .setSp(24, allowFontScalingSelf: true))),
                  ),
                  Expanded(
                    flex: 5,
                    child: Slider(
                      value: model.readerConfig.lineHeight,
                      min: 0.5,
                      max: 2,
                      activeColor: model.theme.expandText,
                      inactiveColor: model.theme.expandActive,
                      divisions: 15,
                      label:
                          "${((model.readerConfig.lineHeight * 10).floor()).toString()}",
                      onChanged: (double val) {
                        model.readerConfig.lineHeight = val;
//                        setState(() {});
                      },
                      onChangeEnd: (double val) {
                        model.setConfig(kReaderLineHeight, val);
                        setState(() {});
                      },
                    ),
                  )
                ],
              ),
            ),
            Container(
              height: ScreenUtil().setHeight(100),
              padding: EdgeInsets.fromLTRB(10, 20, 10, 10),
              child: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Text("左右间距",
                        style: TextStyle(
                            color: model.theme.expandText,
                            fontSize: ScreenUtil()
                                .setSp(24, allowFontScalingSelf: true))),
                  ),
                  Expanded(
                    flex: 5,
                    child: Slider(
                      value: model.readerConfig.padding,
                      min: 0,
                      max: 20,
                      activeColor: model.theme.expandText,
                      inactiveColor: model.theme.expandActive,
                      divisions: 20,
                      label:
                          "${((model.readerConfig.padding).floor()).toString()}",
                      onChanged: (double val) {
                        model.readerConfig.padding = val;
//                        setState(() {});
                      },
                      onChangeEnd: (double val) {
                        model.setConfig(kReaderPadding, val);
                        setState(() {});
                      },
                    ),
                  )
                ],
              ),
            ),
            Container(
              height: ScreenUtil().setHeight(100),
              padding: EdgeInsets.fromLTRB(10, 20, 10, 10),
              child: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Text("主题",
                        style: TextStyle(
                            color: model.theme.expandText,
                            fontSize: ScreenUtil()
                                .setSp(24, allowFontScalingSelf: true))),
                  ),
                  Expanded(
                    flex: 5,
                    child: Container(
                      margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: Row(
                        children: () {
                          var list = <Widget>[];
                          for (var i = 0; i < themeList.length; i++) {
                            list.add(Container(
                              margin: EdgeInsets.fromLTRB(
                                  ScreenUtil().setWidth(36),
                                  0,
                                  ScreenUtil().setWidth(36),
                                  0),
                              padding: EdgeInsets.all(2),
                              width: ScreenUtil().setHeight(50),
                              height: ScreenUtil().setHeight(50),
                              decoration: model.theme.type == i
                                  ? BoxDecoration(
                                      border: Border.all(
                                          color: Color(0xFFfda900), width: 2),
                                      borderRadius: BorderRadius.circular(100))
                                  : BoxDecoration(),
                              child: MaterialButton(
                                onPressed: () {
                                  model.setConfig(kThemeIndex, i,
                                      needState: false);
                                  model.initTheme();
                                },
                                color: i == 0
                                    ? Color(0xFFdcc8a5)
                                    : i == 1
                                        ? Color(0xFF111111)
                                        : i == 2
                                            ? Color(0xFFc7eece)
                                            : Color(0xFFfffef0),
                                shape: RoundedRectangleBorder(
                                    side: BorderSide.none,
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(100))),
                              ),
                            ));
                          }
                          return list;
                        }(),
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _customNavigator(ReaderModel model) {
    return PositionedTransition(
        rect: showToolBar
            ? animationCustomNavigatorOut
            : animationCustomNavigatorEnter,
        child: Container(
          padding: EdgeInsets.fromLTRB(0, AppConfig.statusHeight, 0, 0),
          alignment: Alignment.centerLeft,
          decoration: BoxDecoration(
              color: model.theme.expandBackground,
              border: Border(
                  bottom: BorderSide(color: model.theme.text, width: 0.1)),
              boxShadow: [
                BoxShadow(
                  color: model.theme.expandBackground,
                  offset: Offset(0.0, -2.0),
                  spreadRadius: 0.0,
                  blurRadius: 10.0,
                )
              ]),
          child: Container(
            padding: EdgeInsets.fromLTRB(ScreenUtil().setHeight(10), 0, 0, 0),
            width: ScreenUtil().setWidth(750),
            height: ScreenUtil().setHeight(100) -
                (ScreenUtil().setHeight(1334) - ScreenUtil().setHeight(1334)) /
                    2,
            child: Row(children: <Widget>[
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    //这里应该处理网络请求，关闭正在进行的网络请求
                    FlutterStatusbarManager.setFullscreen(false);
                    FlutterStatusbarManager.setHidden(false);
                    FlutterStatusbarManager.setColor(Colors.transparent);
                    FlutterStatusbarManager.setStyle(StatusBarStyle.DEFAULT);
                    Navigator.pop(context);
                  },
                  child: Image.asset(
                    "assets/images/icon_back.png",
                    color: model.theme.text,
                  ),
                ),
              ),
              Expanded(
                flex: 10,
                child: model.chapterList.length > 0
                    ? Text(
                        "  " + model.chapterList[model.chapterIndex].name,
                        style: TextStyle(
                            color: model.theme.text,
                            fontSize: ScreenUtil()
                                .setSp(30, allowFontScalingSelf: true)),
                      )
                    : Container(),
              ),
              Expanded(
                flex: 2,
                child: GestureDetector(
                  onTap: () {
                    if (model.readMode == ReadMode.empty) {
                      model.readMode = ReadMode.scroll;
                      model.setConfig(kReadeModel, 2, needState: true);
                    } else {
                      model.readMode = ReadMode.empty;
                      model.setConfig(kReadeModel, 1, needState: true);
                    }
                    setDisplayToolBar(
                        backgroundType: 0, statusBarColor: Colors.transparent);
                    setState(() {});
                    Future.delayed(Duration(milliseconds: 100), () {
                      if (model.readMode == ReadMode.empty) {
                        model.pageController
                            .jumpToPage(model.articleList[0].pageCount);
                      } else {
                        model.scrollController.jumpTo(0);
                      }
                    });
                  },
                  child: Text(
                    "切换",
                    style: TextStyle(
                        color: model.theme.text,
                        fontSize:
                            ScreenUtil().setSp(30, allowFontScalingSelf: true)),
                  ),
                ),
              )
            ]),
          ),
        ));
  }

  Widget _buildScrollView(ReaderModel model) {
    if (model.isLoadingArticle) {
      return Container(
        child: Center(
          child: ViewStateBusyWidget(),
        ),
      );
    }
    if (model.articleList[1].pageCount == 0 && !model.isLoadingArticle) {
      return ViewStateReTryWidget(
        color: model.theme.text,
        buttonText: "加载失败，点击重试",
        onPressed: () {
          model.refresh(
            1,
            catalogId: model.articleList[0].nextCatalogId,
            catalogNum: model.articleList[0].nextCatalogNum,
          );
        },
      );
    }
    return GestureDetector(
        child: SingleChildScrollView(
            controller: model.scrollController,
            physics: BouncingScrollPhysics(),
            child: ReaderScrollView(
              article: model.articleList[1],
              fontSize: ScreenUtil().setSp(model.readerConfig.fontSize * 2),
              lineHeight:
                  ScreenUtil().setHeight(model.readerConfig.lineHeight * 2),
              textColor: model.theme.text,
              padding: ScreenUtil().setWidth(model.readerConfig.padding),
              chapterTitle: model.chapterList[model.chapterIndex].name,
              readeAreaHeight: ScreenUtil().setHeight(1334) -
                  ScreenUtil().setWidth(100) -
                  ScreenUtil().setHeight(20),
            )));
  }

  Widget _buildPageView(ReaderModel model) {
    int preCount = model.articleList[0].pageCount != 0
        ? model.articleList[0].pageCount
        : 1;
    int itemCount = model.articleList[1].pageCount != 0
        ? model.articleList[1].pageCount
        : 1;
    int nextCount = model.articleList[2].pageCount != 0
        ? model.articleList[2].pageCount
        : 1;

    return PageView.builder(
      physics: showToolBar
          ? NeverScrollableScrollPhysics()
          : BouncingScrollPhysics(),
      controller: pageController,
      itemCount: preCount + nextCount + itemCount,
      itemBuilder: (context, index) {
        return buildPage(model, index);
      },
      onPageChanged: (int index) {
        model.pageIndex = index;
        if (model.currentChapterId.length < 1 || model.bookId.length < 1) {
          return;
        }
        DatabaseHelper().updateBook(
          update: {"position": model.pageIndex},
          where: "book_id=? ",
          whereArgs: [model.bookId],
        );
//        }
      },
    );
  }

  Widget buildPage(ReaderModel model, int index) {
    Article article;
    int tempIndex = 0; //计算当前章节的index位置
    if (model.isLoadingArticle) {
      return Container(
        child: Center(
          child: ViewStateBusyWidget(),
        ),
      );
    }
    if (index <= model.articleList[0].pageCount - 1) {
      article = model.articleList[0];
      tempIndex = index;
      if (article.pageCount == 0 && !model.isLoadingArticle) {
        return ViewStateReTryWidget(
          color: model.theme.text,
          buttonText: "加载失败，点击重试",
          onPressed: () {
            print("retry1");
          },
        );
      }
    } else if (index <=
        (model.articleList[0].pageCount + model.articleList[1].pageCount) - 1) {
      article = model.articleList[1];
      tempIndex = index - model.articleList[0].pageCount;
      if (article.pageCount == 0 && !model.isLoadingArticle) {
        return ViewStateReTryWidget(
          color: model.theme.text,
          buttonText: "加载失败，点击重试",
          onPressed: () {
            print("retry2");
          },
        );
      }
    } else {
      article = model.articleList[2];
      tempIndex = index -
          model.articleList[0].pageCount -
          model.articleList[1].pageCount;
      if (article.pageCount == 0 && !model.isLoadingArticle) {
        return ViewStateReTryWidget(
          color: model.theme.text,
          buttonText: "加载失败，点击重试",
          onPressed: () {
            print("retry3");
          },
        );
      }
    }
    return GestureDetector(
      child: ReaderView(
        article: article,
        page: tempIndex,
        fontSize: ScreenUtil().setSp(model.readerConfig.fontSize * 2),
        lineHeight: ScreenUtil().setHeight(model.readerConfig.lineHeight * 2),
        textColor: model.theme.text,
        padding: model.readerConfig.padding,
        chapterTitle: model.chapterList[model.chapterIndex].name,
        readeAreaHeight:
            ScreenUtil().setHeight(1334) - ScreenUtil().setWidth(100),
      ),
    );
  }

  Widget _buildChapterContent(ReaderModel model) {
    return DraggableScrollbar(
      controller: _customController,
      child: ListView.builder(
        controller: _customController,
        itemCount: model.chapterList.length,
        itemExtent: itemHeight,
        itemBuilder: (context, index) {
          return _buildChapter(model, index);
        },
      ),
      heightScrollThumb: 28.0,
      backgroundColor: model.theme.background,
      scrollThumbBuilder: (
        Color backgroundColor,
        Animation<double> thumbAnimation,
        Animation<double> labelAnimation,
        double height, {
        Text labelText,
        BoxConstraints labelConstraints,
      }) {
        return FadeTransition(
          opacity: thumbAnimation,
          child: Container(
            height: height,
            width: 20.0,
            decoration: BoxDecoration(
                boxShadow: [
                  BoxShadow(blurRadius: 5, color: Color.fromARGB(40, 0, 0, 0))
                ],
                color: backgroundColor,
                borderRadius: BorderRadius.all(Radius.circular(20))),
          ),
        );
      },
    );
  }

  Widget _buildChapter(ReaderModel model, index) {
    var item = Column(
      children: <Widget>[
        Ink(
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(color: Color(0xFF999999), width: 0.1))),
          child: InkWell(
            onTap: () async {
              bool isNetWork = await isNetWorkAvailable();
              if (!isNetWork && model.chapterList[index].local != 1) return;
              model.currentChapterId = model.chapterList[index].catalogId;
              model.num = model.chapterList[index].num;
              model.chapterIndex = index;
              model.pageIndex = 0;
              model.setContent(
                1,
                catalogId: model.currentChapterId,
                num: model.num,
                fromCache: false,
                force: true,
              );
              print("跳转到指定章节 chapterIndex:${model.chapterIndex}");
              _innerDrawerKey.currentState.close();
            },
            child: Row(
              children: <Widget>[
                Container(
                  padding:
                      EdgeInsets.fromLTRB(ScreenUtil().setWidth(40), 0, 0, 0),
                  height: ScreenUtil().setHeight(99),
                  alignment: Alignment.centerLeft,
                  child: Stack(
                    overflow: Overflow.visible,
                    children: <Widget>[
                      Container(
                        width: ScreenUtil().setWidth(750 * 0.6),
                        padding:
                            EdgeInsets.only(right: ScreenUtil().setWidth(100)),
                        child: Text(
                          model.chapterList[index].name,
                          style: TextStyle(
                              fontSize: 14,
                              color: model.chapterIndex == index
                                  ? model.theme.background.withGreen(100)
                                  : model.theme.text),
                        ),
                      ),
//
                    ],
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );
    return item;
  }

  Future<bool> _willPopHandle() async {
    if (showToolBar) {
      setDisplayToolBar(backgroundType: 0, statusBarColor: Colors.transparent);
      return Future.value(false);
    }
    if (innerDrawerIsOpen) {
      _innerDrawerKey.currentState.close();
    }
    FlutterStatusbarManager.setFullscreen(false);
    FlutterStatusbarManager.setHidden(false);
    FlutterStatusbarManager.setColor(Colors.transparent);
    FlutterStatusbarManager.setStyle(StatusBarStyle.DEFAULT);
    EventBus().emit("bookSheetRefresh");
    AppConfig.router.pop(context);
    return Future.value(false);
  }

  Future<bool> isNetWorkAvailable() async {
    var connectivityResult = await (new Connectivity().checkConnectivity());

    if (connectivityResult == ConnectivityResult.mobile ||
        connectivityResult == ConnectivityResult.wifi)
      return true;
    else
      return false;
  }
}
